package com.example.spring.demo.common.local;

/**
 * @author qwert
 * @version 1.0.0
 * @create 2024/12/31 14:18
 **/
import cn.hutool.core.util.StrUtil;
import com.example.spring.demo.common.error.CustomException;
import com.example.spring.demo.common.error.ErrorCodeEnum;
import com.example.spring.demo.service.TokenService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;
import java.util.Objects;

@Component
public class UserContextInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 设置ThreadLocal数据，例如从请求头或会话中提取用户信息
        String token = request.getHeader("X-User-Token");
//        String token = request.getHeader("token");
        if(StrUtil.isNotEmpty(token)) {
            // select to DB
            Map<String, Object> chaims = JwtUtil.parseToken(token);
            Integer userId = (Integer) chaims.get("userId");
            String username = chaims.get("username").toString();

            String tokenKey = userId + token;
            String dbToken = tokenService.getToken(tokenKey);
            if(!Objects.equals(token, dbToken)) {
                throw new CustomException(ErrorCodeEnum.USER_LOG_ERROR);
            }

            UserContextHolder.setContext(UserContext.builder()
                    .userId(userId)
                    .username(username)
                    .build());
        } else {
            UserContextHolder.setContext(UserContext.builder()
                    .username("未知用户")
                    .build());
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求结束后清除ThreadLocal数据
        UserContextHolder.clearContext();
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 如果需要，可以在postHandle中进行额外的操作
    }
}
